<template>
  <div class="address-edit-container">
    <div class="page-header">
      <h1 class="title">{{ isEdit ? "编辑收货地址" : "新增收货地址" }}</h1>
    </div>

    <div class="edit-form">
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="收货人" name="consignee">
          <a-input
            v-model:value="formState.consignee"
            placeholder="请输入收货人姓名"
          />
        </a-form-item>

        <a-form-item label="手机号码" name="phone">
          <a-input
            v-model:value="formState.phone"
            placeholder="请输入手机号码"
          />
        </a-form-item>

        <a-form-item
          label="所在地区"
          name="region"
          :rules="[
            { required: true, validator: validateRegion, trigger: 'change' },
          ]"
        >
          <div class="region-select">
            <div class="selected-region" @click="showRegionModal">
              <span v-if="selectedRegionNames.length">
                {{ selectedRegionNames.join(" ") }}
              </span>
              <span v-else class="placeholder">请选择省/市/区</span>
              <DownOutlined />
            </div>
          </div>
        </a-form-item>

        <a-form-item label="详细地址" name="detail">
          <a-textarea
            v-model:value="formState.detail"
            :rows="4"
            placeholder="请输入详细地址，如街道名称、门牌号等"
          />
        </a-form-item>

        <a-form-item label="地址标签" name="label">
          <a-input
            v-model:value="formState.label"
            placeholder="如：家、公司等（选填）"
          />
        </a-form-item>

        <a-form-item label="设为默认" name="isDefault">
          <a-switch
            :checked="formState.isDefault === 1"
            @change="(checked: boolean) => formState.isDefault = checked ? 1 : 0"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-space>
            <a-button type="primary" @click="handleSubmit">保存</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <!-- 地区选择弹窗 -->
    <a-modal
      v-model:visible="regionModalVisible"
      title="选择地区"
      :footer="null"
      width="680px"
    >
      <div class="region-selector">
        <div class="region-tabs">
          <div
            class="tab-item"
            :class="{ active: currentTab === 'province' }"
            @click="switchTab('province')"
          >
            <span>{{ selectedRegionNames[0] || "请选择省" }}</span>
          </div>
          <div
            v-if="currentTab !== 'province'"
            class="tab-item"
            :class="{ active: currentTab === 'city' }"
            @click="switchTab('city')"
          >
            <span>{{ selectedRegionNames[1] || "请选择市" }}</span>
          </div>
          <div
            v-if="currentTab === 'district'"
            class="tab-item"
            :class="{ active: currentTab === 'district' }"
          >
            <span>{{ selectedRegionNames[2] || "请选择区" }}</span>
          </div>
        </div>

        <div class="region-list">
          <template v-if="currentTab === 'province'">
            <div
              v-for="province in provinceList"
              :key="province.code"
              class="region-item"
              :class="{
                active: selectedRegion.province?.code === province.code,
              }"
              @click="selectProvince(province)"
            >
              {{ province.name }}
            </div>
          </template>

          <template v-if="currentTab === 'city'">
            <div
              v-for="city in cityList"
              :key="city.code"
              class="region-item"
              :class="{ active: selectedRegion.city?.code === city.code }"
              @click="selectCity(city)"
            >
              {{ city.name }}
            </div>
          </template>

          <template v-if="currentTab === 'district'">
            <div
              v-for="district in districtList"
              :key="district.code"
              class="region-item"
              :class="{
                active: selectedRegion.district?.code === district.code,
              }"
              @click="selectDistrict(district)"
            >
              {{ district.name }}
            </div>
          </template>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import type { FormInstance } from "ant-design-vue";
import {
  saveUsingPost,
  updateUsingPost,
  getUsingPost,
} from "@/api/addressBookController";
import type API from "@/api";
import { DownOutlined } from "@ant-design/icons-vue";
import {
  listProvincesUsingGet,
  listCitiesUsingPost,
  listDistrictsUsingPost,
} from "@/api/regionDictController";

const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();
const isEdit = ref(false);

const formState = reactive<API.AddressBook>({
  consignee: "",
  phone: "",
  provinceName: "",
  cityName: "",
  districtName: "",
  provinceCode: "",
  cityCode: "",
  districtCode: "",
  detail: "",
  label: "",
  isDefault: 0,
});

const rules = {
  consignee: [{ required: true, message: "请输入收货人姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  detail: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
};

const selectedRegion = ref<{
  province?: API.RegionDict;
  city?: API.RegionDict;
  district?: API.RegionDict;
}>({});

// 计算选中的地区名称
const selectedRegionNames = computed(() => {
  const names: string[] = [];
  if (selectedRegion.value.province)
    names.push(selectedRegion.value.province.name);
  if (selectedRegion.value.city) names.push(selectedRegion.value.city.name);
  if (selectedRegion.value.district)
    names.push(selectedRegion.value.district.name);
  return names;
});

// 地区选择相关状态
const regionModalVisible = ref(false);
const currentTab = ref<"province" | "city" | "district">("province");
const provinceList = ref<API.RegionDict[]>([]);
const cityList = ref<API.RegionDict[]>([]);
const districtList = ref<API.RegionDict[]>([]);

// 显示地区选择弹窗
const showRegionModal = async () => {
  regionModalVisible.value = true;
  if (!provinceList.value.length) {
    await loadProvinces();
  }
};

// 加载省份列表
const loadProvinces = async () => {
  try {
    const res = await listProvincesUsingGet();
    if (res.data?.code === 0 && res.data.data) {
      provinceList.value = res.data.data;
    }
  } catch (error) {
    console.error("加载省份列表失败:", error);
  }
};

// 加载城市列表
const loadCities = async (parentCode: string) => {
  try {
    const res = await listCitiesUsingPost({ parentCode });
    if (res.data?.code === 0 && res.data.data) {
      cityList.value = res.data.data;
    }
  } catch (error) {
    console.error("加载城市列表失败:", error);
  }
};

// 加载区县列表
const loadDistricts = async (parentCode: string) => {
  try {
    const res = await listDistrictsUsingPost({ parentCode });
    if (res.data?.code === 0 && res.data.data) {
      districtList.value = res.data.data;
    }
  } catch (error) {
    console.error("加载区县列表失败:", error);
  }
};

// 选择省份
const selectProvince = async (province: API.RegionDict) => {
  selectedRegion.value = { province };
  formState.provinceName = province.name;
  formState.provinceCode = province.code;
  await loadCities(province.code);
  currentTab.value = "city";
};

// 选择城市
const selectCity = async (city: API.RegionDict) => {
  selectedRegion.value = {
    ...selectedRegion.value,
    city,
  };
  formState.cityName = city.name;
  formState.cityCode = city.code;
  await loadDistricts(city.code);
  currentTab.value = "district";
};

// 选择区县
const selectDistrict = (district: API.RegionDict) => {
  selectedRegion.value = {
    ...selectedRegion.value,
    district,
  };
  // 更新表单数据
  formState.districtName = district.name;
  formState.districtCode = district.code;

  // 手动触发表单验证
  formRef.value?.validateFields(["region"]);

  regionModalVisible.value = false;
};

// 切换标签页
const switchTab = (tab: "province" | "city" | "district") => {
  currentTab.value = tab;
};

// 添加地区验证函数
const validateRegion = async (_rule: any, _value: any) => {
  if (
    !formState.provinceName ||
    !formState.cityName ||
    !formState.districtName ||
    !formState.provinceCode ||
    !formState.cityCode ||
    !formState.districtCode
  ) {
    return Promise.reject("请选择完整的省市区信息");
  }
  return Promise.resolve();
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    const api = isEdit.value ? updateUsingPost : saveUsingPost;

    // 确保所有必要的地区信息都存在
    if (
      !formState.provinceName ||
      !formState.cityName ||
      !formState.districtName
    ) {
      message.error("请选择完整的省市区信息");
      return;
    }

    const res = await api(formState);
    if (res.data?.code === 0) {
      message.success(isEdit.value ? "修改成功" : "添加成功");
      router.back();
    }
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message);
    } else {
      message.error("表单验证失败");
    }
  }
};

// 取消
const handleCancel = () => {
  router.back();
};

// 加载编辑数据
const loadEditData = async (id: number) => {
  try {
    const res = await getUsingPost({ id });
    if (res.data?.code === 0 && res.data.data) {
      // 确保 isDefault 是数字类型
      const addressData = {
        ...res.data.data,
        isDefault: res.data.data.isDefault ? 1 : 0,
      };
      Object.assign(formState, addressData);

      // 设置选中的地区信息
      if (
        formState.provinceName &&
        formState.cityName &&
        formState.districtName
      ) {
        selectedRegion.value = {
          province: {
            name: formState.provinceName,
            code: formState.provinceCode,
          } as API.RegionDict,
          city: {
            name: formState.cityName,
            code: formState.cityCode,
          } as API.RegionDict,
          district: {
            name: formState.districtName,
            code: formState.districtCode,
          } as API.RegionDict,
        };

        // 更新选中的地区名称
        selectedRegionNames.value = [
          formState.provinceName,
          formState.cityName,
          formState.districtName,
        ];
      }
    }
  } catch (error) {
    message.error("获取地址信息失败");
  }
};

onMounted(() => {
  const id = route.params.id;
  if (id) {
    isEdit.value = true;
    loadEditData(Number(id));
  }
});
</script>

<style scoped>
.address-edit-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
  background: #fff;
  border-radius: 4px;
}

.page-header {
  margin-bottom: 24px;
}

.title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.edit-form {
  padding: 24px;
  background: #fff;
}

.region-select {
  width: 100%;
}

.selected-region {
  border: 1px solid #d9d9d9;
  padding: 4px 11px;
  border-radius: 2px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.placeholder {
  color: #bfbfbf;
}

.region-selector {
  padding: 16px;
}

.region-tabs {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
}

.tab-item {
  padding: 8px 16px;
  cursor: pointer;
  color: #666;
}

.tab-item.active {
  color: #1890ff;
  font-weight: 500;
}

.region-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.region-item {
  padding: 8px 16px;
  text-align: center;
  cursor: pointer;
  border-radius: 2px;
}

.region-item:hover {
  background: #f5f5f5;
}

.region-item.active {
  background: #e6f7ff;
  color: #1890ff;
}

/* 添加标签输入框样式 */
.ant-form-item-label > label {
  color: #666;
}
</style>
